package com.anysoft.guide;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.GetStartupAdvertisementBean;
import com.anysoft.home.HomeActivity;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.image.MyBitmapUtils;
import com.anysoft.view.CountDownView;
import com.anysoft.web.BannerUrlActivity;
import com.anysoft.web.FundDetailActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by wwq on 2016/12/6.
 */

public class GuideCountDownActivity extends BaseActivity {

    @BindView(R.id.iv_count_down_bg)
    ImageView ivCountDownBg;
    @BindView(R.id.count_down_view)
    CountDownView countDownView;
    private int progress = 0;

    private CountDownView count_down_view;
    private boolean isCanClick = false;
    private boolean isCountDownCanClick = false;

    private String imgUrl = "http://p19.qhimg.com/t01f797c7fe7a9f6448.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guide_count_down_activity);
        ButterKnife.bind(this);

        getStartupAdvertisement();
        initView();
    }

    private void getStartupAdvertisement() {
        Map<String, String> params = new HashMap<>();
        params.put("id", "");//(可选)，填写后，将传回查询的广告，不传，则传回最新的一条广告
//        params.put("id", "802");//(可选)，填写后，将传回查询的广告，不传，则传回最新的一条广告---基金详情的id
//        params.put("id", "798");//(可选)，填写后，将传回查询的广告，不传，则传回最新的一条广告---普通广告的id
        OkGo.<String>post(HostConstant.GET_STARTUP_ADVERTISEMENT)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.Log(TAG + "获取APP登录广告:", response.body());
                        updateUI(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private GetStartupAdvertisementBean bean;

    private void updateUI(String resultJson) {
        try {
            bean = new Gson().fromJson(resultJson, GetStartupAdvertisementBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, resultJson)) {
            return;
        }

        if (bean != null && bean.getData() != null && !TextUtils.isEmpty(bean.getData().getImage())) {
            isCanClick = true;
            new MyBitmapUtils().disPlay(ivCountDownBg, bean.getData().getImage());
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {

        count_down_view = (CountDownView) findViewById(R.id.count_down_view);
        count_down_view.setCountDownTimerListener(new CountDownView.CountDownTimerListener() {
            @Override
            public void onStartCount() {
                Logger.d(TAG, "开始计时");
            }

            @Override
            public void onFinishCount() {
                Logger.d(TAG, "结束计时");
                if (isGotoHome) {
                    startActivity(new Intent().setClass(GuideCountDownActivity.this, HomeActivity.class));
                    finish();
                }
            }
        });
        count_down_view.start();
    }

    private boolean isGotoHome = true;

    @OnClick({R.id.iv_count_down_bg, R.id.count_down_view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_count_down_bg:
                if (isCanClick) {
                    showToast("点击广告图片~~~");
                    if (bean != null && bean.getData() != null) {
                        String pathUrl = bean.getData().getUrl();
                        if (!TextUtils.isEmpty(pathUrl)) {
                            if (pathUrl.contains("fundDetail.html")) {
                                String url = null;
                                try {
                                    url = URLDecoder.decode(pathUrl, "utf-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                MentorLogger.Log(TAG, "url=" + url);
                                String fundcode;
                                String fundType;
                                String mainTitle;
                                String subTitle;
                                Map<String, String> map = new HashMap<>();
                                String[] params = url.split("\\?")[1].split("&");
                                for (int i = 0; i < params.length; i++) {
                                    //System.out.println("params--" + params[i]);
                                    String key = params[i].split("=")[0];
                                    String value = "";
                                    try {
                                        value = params[i].split("=")[1];
                                    } catch (Exception exception) {
                                        MentorLogger.Log(TAG, "value为null");
                                    }
                                    map.put(key, value);
                                }
                                fundcode = map.get("fundCode");
                                fundType = map.get("fundType");
                                mainTitle = map.get("fundname") + "  " + map.get("fundCode");
                                subTitle = map.get("fundstateDescription");

                                Intent mIntent = new Intent();
                                mIntent.setClass(mActivity, FundDetailActivity.class);
                                mIntent.putExtra("fundcode", fundcode);
                                mIntent.putExtra("fundType", fundType);
                                mIntent.putExtra("fundname", map.get("fundname"));
                                mIntent.putExtra("mainTitle", mainTitle);
                                mIntent.putExtra("subTitle", subTitle);
                                mIntent.putExtra("isFromGuide", true);
                                startActivity(mIntent);
                                isGotoHome = false;
                                count_down_view.stopTimer();
                                finish();
                            } else {
                                Intent intent = new Intent();
                                intent.setClass(mActivity, BannerUrlActivity.class);
                                intent.putExtra("bannerUrl", bean.getData().getUrl());
                                intent.putExtra("isFromGuide", true);
                                startActivity(intent);
                                isGotoHome = false;
                                count_down_view.stopTimer();
                                finish();
                            }
                        }
                    }
                }
                break;
            case R.id.count_down_view:
                startActivity(new Intent().setClass(GuideCountDownActivity.this, HomeActivity.class));
                count_down_view.stopTimer();
                finish();
                break;
        }
    }
}
